/**
 * 参数说明：
 * maskDivClass 为mask层新添加的类，
 * opacity 		mask层的透明度
 * z			mask层的z-index
 * bgcolor		mask层的背景色
 * msg			mask层显示的文字
 * img 			mask层文字前的图片，一般是一个小动画文件
 */
(function() {
	$.extend($.fn, {
		mask : function(setting) {
			this.unmask();
			var op = {
				opacity 	: 0.8,
				z 			: 9999,
				bgcolor 	: '#ccc',
				msg			: '请等待...',
				img			: 'res/img/loading.gif',
				maskDivClass: ''
			};
			
			op = $.extend(op,setting);
			
			var original = $(document.body);

			var position = {
				top : 0,
				left : 0
			};

			if (this[0] && this[0] !== window.document) {
				original = this;
				position = original.position();
			}

			var maskDiv = $('<div class="maskdivgen"> </div>');
			maskDiv.appendTo(original);

			var maskWidth = original.outerWidth();
			if (!maskWidth) {
				maskWidth = original.width();
			}

			var maskHeight = original.outerHeight();
			if (!maskHeight) {
				maskHeight = original.height();
			}

			maskDiv.css({
						position : 'absolute',
						top : position.top,
						left : position.left,
						'z-index' : op.z,
						width : maskWidth,
						height : maskHeight,
						'background-color' : op.bgcolor,
						opacity : 0
					});

			if (op.maskDivClass && op.maskDivClass != '') {
				maskDiv.addClass(op.maskDivClass);
			}

			if (op.msg) {
//				var msgDiv = $('<div style="position:absolute;border:#6593cf 1px solid; padding:2px;background:#ccca">' +
//							'<div style="line-height:24px;border:#a3bad9 1px solid;background:white;padding:2px 10px 2px 10px">'
//							+ op.msg + '</div></div>');
				var msgDiv = $('<div></div>').css({
								position:'absolute',
								border:'#6593cf 1px solid', 
								padding:'2px',
								background:'#ccca',
								'text-align':'center'
							});
				var msgDiv_imgDiv = $('<div style="line-height:24px;border:#a3bad9 1px solid;background:white;padding:2px 10px 2px 10px"></div>');
				if(op.img != ''){
					msgDiv_imgDiv.append($('<img/>').attr('src',op.img));
				}
				
				msgDiv_imgDiv.append(op.msg);
				msgDiv_imgDiv.appendTo(msgDiv);
				
				msgDiv.appendTo(maskDiv);
				var widthspace = (maskDiv.width() - msgDiv.width());
				var heightspace = (maskDiv.height() - msgDiv.height());
				msgDiv.css({
							top : (heightspace / 2 - 2),
							left : (widthspace / 2 - 2)
						});
				maskDiv.css({cursor : 'wait'});
			}

			maskDiv.fadeIn('fast', function() {
						$(this).fadeTo('slow', op.opacity);
					});
			return maskDiv;
		},
		unmask : function() {
			var original = $(document.body);
			if (this[0] && this[0] !== window.document) {
				original = $(this[0]);
			}
			
			original.find("> div.maskdivgen").fadeOut('slow', 0, function() {
						$(this).remove();
					});
		}
	});
})();